/*
 * This servlet controls the Payment page view
 *
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.Cart;
import classes.HibernateUtil;
import dao.CourseDao;
import dao.PaymentDao;
import dao.PaymethodDao;
import dao.StudentDao;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;
import models.Payment;
import models.Paymethod;
import models.Student;
import models.User;

/**
 *
 * @author Michel
 */
public class PaymentController extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private Paymethod pmget = new Paymethod();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        HibernateUtil hu = new HibernateUtil();
        PaymethodDao pmd = new PaymethodDao(hu.openSession());
        List<Paymethod> pml = pmd.findAll();
        request.setAttribute("methods", pml);
        hu.close();

        //checks parameter idremove is not null then removemethod is called
        if (request.getParameter("idremove") != null) {
            removemethod(Long.parseLong(request.getParameter("idremove")), request, response);

            //checks if parameter add is not null when idremove does not exist    
        } else if (request.getParameter("add") != null) {
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Payment", "Manage payment methods"),
                new Breadcrumbs("Payment?add", "Add payment method")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
            request.getRequestDispatcher("jsp/add_edit_payment.jsp").forward(request, response);

            //checks if id is not null when add and idremove do not exist
            // sets the breadcrumbs and calls the editpaymentmethod
        } else if (request.getParameter("id") != null) {
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Payment", "Manage payment methods"),
                new Breadcrumbs("Payment?id", "Edit payment method")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
            editpaymentmethod(Long.parseLong(request.getParameter("id")), request, response);

            //handels the breadcrumbs and pageview of the payment page
        } else {
            if (session.getAttribute("selected") != null) {
                request.setAttribute("selected", session.getAttribute("selected"));
                session.setAttribute("selected", null);
            }
            //check step and set step and breadcrumb
            if (request.getParameter("next") == null) {
                request.setAttribute("step", 1);
                // Breadcrumbs
                Breadcrumbs[] breadcrumbs = {
                    new Breadcrumbs("Index", "Home"),
                    new Breadcrumbs("Payment", "Manage payment methods")
                };
                request.setAttribute("breadcrumbs", breadcrumbs);
            
            //check step and set step and breadcrumb    
            } else if (request.getParameter("next").equals("1")) {
                request.setAttribute("step", 1);
                // Breadcrumbs
                Breadcrumbs[] breadcrumbs = {
                    new Breadcrumbs("Index", "Home"),
                    new Breadcrumbs("Payment?next=1", "Cart"),
                    new Breadcrumbs("Payment?next=1", "Step 1")
                };
                request.setAttribute("breadcrumbs", breadcrumbs);
                
            //check step and set step and breadcrumb
            } else if (request.getParameter("next").equals("2")) {
                request.setAttribute("step", 2);
                // Breadcrumbs
                Breadcrumbs[] breadcrumbs = {
                    new Breadcrumbs("Index", "Home"),
                    new Breadcrumbs("Payment?next=1", "Cart"),
                    new Breadcrumbs("Payment?next=2", "Step 2")
                };
                request.setAttribute("breadcrumbs", breadcrumbs);
                
            //check step and set step and breadcrumb
            } else if (request.getParameter("next").equals("3")) {
                request.setAttribute("step", 3);
                // Breadcrumbs
                Breadcrumbs[] breadcrumbs = {
                    new Breadcrumbs("Index", "Home"),
                    new Breadcrumbs("Payment?next=1", "Cart"),
                    new Breadcrumbs("Payment?next=3", "Step 3")
                };
                request.setAttribute("breadcrumbs", breadcrumbs);
                Paymethod pm = pmd.get(Long.parseLong(request.getParameter("select")));
                request.setAttribute("selectmethod", pm);
            }
            
            //if the cart is not null get the cart session
            if (request.getSession().getAttribute("cart") != null) {
                Cart cart = (Cart) request.getSession().getAttribute("cart");
                request.setAttribute("cartx", cart.getTotalPrice());
                request.setAttribute("carta", cart.getAmount());
            } else {
                request.setAttribute("cartx", 0);
                request.setAttribute("carta", 0);
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/payment.jsp");
            dispatcher.forward(request, response);
        }


    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (request.getParameter("formoption").equals("finishpayment")) {
            Cart cart = (Cart) request.getSession().getAttribute("cart");
            List<Course> cartcourse = cart.getCart();

            //----------------------------------------------------------------------
            //Set ordered courses in course_student table
            //----------------------------------------------------------------------


            HibernateUtil hu = new HibernateUtil();
            StudentDao sd = new StudentDao(hu.openSession());
            CourseDao cd = new CourseDao(hu.openSession());

            for (int i = 0; i < cartcourse.size(); i++) {
                Course c = cd.get(cartcourse.get(i).getId());
                Set<Student> st = c.getStudent();

                Student student = sd.get(user.getMember_id());

                st.add(student);

                cd.update(c);

            }


            //----------------------------------------------------------------------
            //Set order in payment
            //----------------------------------------------------------------------    
            PaymentDao pd = new PaymentDao(hu.openSession());
            StudentDao stud = new StudentDao(hu.openSession());
            Student student = stud.get(user.getMember_id());
            long id = System.nanoTime();
            String creditcardNumber = request.getParameter("creditcardnumber");
            Payment payment = new Payment(id, creditcardNumber, student);
            payment.setMethod(this.getPmget());
            pd.save(payment);
            session.setAttribute("cart", null);
            request.setAttribute("step", null);
            request.setAttribute("selectmethod", null);

            if (cartcourse.size() == 1) {
                response.sendRedirect("Course?courseid=" + cartcourse.get(0).getId());
            } else {
                response.sendRedirect("Index");
            }
        } else if (request.getParameter("formoption").equals("methodselect")) {
            session.setAttribute("selected", request.getParameter("methodoption"));
            HibernateUtil hu = new HibernateUtil();
            PaymethodDao pmd = new PaymethodDao(hu.openSession());
            Paymethod p = pmd.get(Long.parseLong(request.getParameter("methodoption")));
            this.setPmget(p);
            response.sendRedirect("Payment?next=2&selected=" + request.getParameter("methodoption"));
        } else {
            if (request.getParameter("formoption").equals("add")) {
                HibernateUtil hu = new HibernateUtil();
                PaymethodDao pmd = new PaymethodDao(hu.openSession());
                long id = System.nanoTime();
                String name = request.getParameter("name");
                String link = request.getParameter("link");
                Paymethod paymet = new Paymethod(id, name, link);
                pmd.save(paymet);
                hu.close();
            }
            if (request.getParameter("formoption").equals("edit")) {
                HibernateUtil hu = new HibernateUtil();
                PaymethodDao pmd = new PaymethodDao(hu.openSession());
                Long id = Long.parseLong(request.getParameter("methodid"));
                String name = request.getParameter("name");
                String link = request.getParameter("link");
                Paymethod paymet = new Paymethod(id, name, link);
                pmd.update(paymet);
                hu.close();
            }
            response.sendRedirect("Payment");
        }
    }

    private void editpaymentmethod(long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        PaymethodDao pmd = new PaymethodDao(hu.openSession());
        List<Paymethod> methodList = pmd.findAll();
        Paymethod temp = null;
        for (int i = 0; i < methodList.size(); i++) {
            if (methodList.get(i).getId() == id) {
                temp = methodList.get(i);
                System.out.println("got a match");
            }
        }
        hu.close();
        if (temp != null) {
            request.setAttribute("methodedit", temp);
        }

        request.getRequestDispatcher("jsp/add_edit_payment.jsp").forward(request, response);
    }

    private void removemethod(long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        PaymethodDao mpd = new PaymethodDao(hu.openSession());
        Paymethod pm = mpd.get(id);
        mpd.delete(pm);
        hu.close();
        response.sendRedirect("Payment");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public Paymethod getPmget() {
        return pmget;
    }

    public void setPmget(Paymethod pmget) {
        this.pmget = pmget;
    }
}
